//
//	MME+GlobalSymbols.m -- merge engine global symbol table handlers
//		Written by Don Yacktman Copyright (c) 1995 by Don Yacktman.
//				Version 1.0.  All rights reserved.
//		This notice may not be removed from this source code.
//
//	This object is included in the MiscKit by permission from the author
//	and its use is governed by the MiscKit license, found in the file
//	"LICENSE.rtf" in the MiscKit distribution.  Please refer to that file
//	for a list of all applicable permissions and restrictions.
//	


#import <misckit/misckit.h>
#import <misckit/MiscMergeEngine.h>


@implementation MiscMergeEngine (GlobalSymbols)

// Handling a global symbol table
static MiscDictionary *globalSymbolTable = nil;

+ resetGlobalSymbolTable
/*" Empties the global symbol table.  Returns self.
"*/
{	// we don't free values--this could leak memory
	if (globalSymbolTable) {
		[globalSymbolTable freeObjects];
		[globalSymbolTable free];
	}
	globalSymbolTable = [[MiscDictionary alloc] init];
	return self;
}

+ setGlobalSymbol:name toValue:val
/*" Sets the global symbol %{name} to have the value %{val}.
Returns self.
"*/
{
	if (!globalSymbolTable) [self resetGlobalSymbolTable];
	[val squashSpaces]; // just to be safe
	[globalSymbolTable insertKey:name value:val];
	return self;
}

+ addDictionaryToGlobalSymbols:(MiscDictionary *)aDictionary
/*" Adds the contents of %{aDictionary} to the global symbol table.
Returns self.  #{%{Warning:}  This is currently unimplemented.}
"*/
{
	// ***** iterate through dictionary and copy symbols over verbatim
	if (!globalSymbolTable) [self resetGlobalSymbolTable];
	return self;
}

+ addListToGlobalSymbols:(List *)aList
/*" Adds the contents of %{aList} to the global symbol table.
Returns self.  The keys for the List's contents are generated
as ªf0º, ªf1º, and so on.
"*/
{
	int i; id name = [MiscString new];
	for (i=0; i<[aList count]; i++) {
		id val = [aList objectAt:i];
		[name setFromFormat:"f%d", (i+1)];
		if ([val isKindOf:([MiscString class])])
			[self setGlobalSymbol:name toValue:val];
	}
	return self;
}

+ (MiscString *)globalSymbolForKey:(MiscString *)name
/*" Returns the value for the global symbol %{name}, if found.  Returns nil
if not found.
"*/
{
	if (!globalSymbolTable) [self resetGlobalSymbolTable];
	if (!name || ![name length] || ![name stringValue]) return nil;
	if ([globalSymbolTable isKey:name])
		return (MiscString *)[globalSymbolTable
				valueForKey:name];
	return nil; // don't have it...
}

@end
